import { useEffect, useMemo, useState } from 'react'
import dayjs from 'dayjs'
import { Button, Card, Col, Input, message, Row, Space, Tag, Typography } from 'antd'

import { apiSetIsaBl } from '../../apis'
import { useBoundStore } from '../../store'
import { useUrlParams } from '../../utils'
import styles from './styles.module.less'

type TSlotStatus = 'available' | 'crowded' | 'priority' | 'unavailable'

type TFilter = '全部' | '可用' | '拥挤' | '优先' | '无法入仓'

interface ISlotItem {
  id: string
  weekLabel: string
  /** 时间范围 */
  dateRange: [string, string]
  /** 可更改截止时间 */
  changeDeadline?: string
  /** 拥挤程度有效时间 */
  crowdedEffectiveTime?: string
  status: TSlotStatus
}

const StatusTag = ({ status }: { status: TSlotStatus }) => {
  switch (status) {
    case 'available':
      return <Tag color="success">可用</Tag>
    case 'crowded':
      return <Tag color="orange">拥挤</Tag>
    case 'priority':
      return <Tag color="processing">优先</Tag>
    case 'unavailable':
      return <Tag color="error">无法入仓</Tag>
    default:
      return null
  }
}

export const DeliveryReservation = () => {
  const { waybillNo } = useUrlParams()
  const detail = useBoundStore(state => state.detail)
  const [isaVal, setIsaVal] = useState<string>('')
  const [blVal, setBlVal] = useState<string>('')
  const [filter, setFilter] = useState<TFilter>('全部')
  const [selectedId, setSelectedId] = useState<string>('DW-001')

  // 模拟时段数据（后续可换成接口返回）
  const slots = useMemo<ISlotItem[]>(
    () => [
      {
        id: 'DW-001',
        weekLabel: '第5周',
        dateRange: ['2025-01-27', '2025-02-02'],
        changeDeadline: '2025-01-26',
        crowdedEffectiveTime: '2025/01/25 18:00',
        status: 'available',
      },
      {
        id: 'DW-002',
        weekLabel: '第6周',
        dateRange: ['2025-02-03', '2025-02-09'],
        changeDeadline: '2025-02-02',
        crowdedEffectiveTime: '2025/01/25 18:00',
        status: 'crowded',
      },
      {
        id: 'DW-003',
        weekLabel: '第7周',
        dateRange: ['2025-02-10', '2025-02-16'],
        changeDeadline: '2025-02-09',
        crowdedEffectiveTime: '2025/01/25 18:00',
        status: 'priority',
      },
      {
        id: 'DW-004',
        weekLabel: '第8周',
        dateRange: ['2025-02-17', '2025-02-23'],
        changeDeadline: '2025-02-16',
        crowdedEffectiveTime: '2025/01/25 18:00',
        status: 'unavailable',
      },
    ],
    [],
  )

  const infoBox = [
    {
      label: 'FBA仓库代码',
      value: (detail as any)?.destinationCode || 'LAX4',
    },
    {
      label: 'FBA ID',
      value: (detail as any)?.fbaId || 'FBA15GQZC9XK',
    },
    {
      label: '地址',
      value: (detail as any)?.referenceId || 'REF-20250130-001',
    },
    {
      label: 'Reference ID',
      value: 'REF-20250130-001',
    },
  ]

  const filteredSlots = useMemo(() => {
    if (filter === '全部') return slots
    const map: Record<Exclude<TFilter, '全部'>, TSlotStatus> = {
      可用: 'available',
      拥挤: 'crowded',
      优先: 'priority',
      无法入仓: 'unavailable',
    }
    return slots.filter(s => s.status === map[filter])
  }, [filter, slots])

  const selectedSlot = useMemo(() => slots.find(s => s.id === selectedId), [selectedId, slots])

  const updateIsaBl = async () => {
    if (detail.isa === isaVal && detail.bl === blVal) return false
    await apiSetIsaBl({
      isa: isaVal,
      bl: blVal,
      waybillNo,
    })
  }

  const reserve = () => {
    if (!selectedSlot) return
    updateIsaBl()
    message.success(
      `已预约送达时段：${selectedSlot.weekLabel} ${dayjs(selectedSlot.dateRange[0]).format('MM-DD')} ~ ${dayjs(
        selectedSlot.dateRange[1],
      ).format('MM-DD')}`,
    )
  }

  useEffect(() => {
    setIsaVal(detail?.isa || '')
    setBlVal(detail?.bl || '')
  }, [detail])

  return (
    <Card
    // title={
    //   <Space align="center">
    //     <Typography.Title level={5} style={{ marginBottom: 0 }}>
    //       派送预约
    //     </Typography.Title>
    //     {/* <Tag bordered={false}>待选择</Tag> */}
    //   </Space>
    // }
    // extra={
    //   <Space>
    //     <Space.Compact direction="vertical">
    //       <Typography.Text className={classNames('small_print', 'small_print_strong', styles.right_text)}>
    //         已预约送达时段
    //       </Typography.Text>
    //       <Typography.Text className={styles.right_text_time}>
    //         {selectedSlot
    //           ? `${selectedSlot.weekLabel} ${dayjs(selectedSlot.dateRange[0]).format('MM-DD')} ~ ${dayjs(
    //               selectedSlot.dateRange[1],
    //             ).format('MM-DD')}`
    //           : '-'}
    //       </Typography.Text>
    //     </Space.Compact>
    //   </Space>
    // }
    >
      {/* 基本信息区 */}
      {/* <div className={styles.infoBox}>
        <Row gutter={16}>
          {infoBox.map(item => (
            <Col span={12} key={item.label} className={styles.infoBox_item}>
              <Space size={4} direction="vertical">
                <Typography.Text type="secondary" className={classNames('small_print', 'small_print_strong')}>
                  {item.label}
                </Typography.Text>
                <Typography.Text strong className={styles.infoBox_value}>
                  {item.value}
                </Typography.Text>
              </Space>
            </Col>
          ))}
        </Row>
      </div>
      <Divider /> */}
      {/* 预约信息区 */}
      {/* <Typography.Title level={5} style={{ marginTop: 8 }}>
        预约信息
      </Typography.Title>
      <Row style={{ marginBottom: 8 }}>
        <Col span={12}>
          <Space direction="vertical" size={4}>
            <Typography.Text type="secondary" className={classNames('small_print', 'small_print_strong')}>
              预计送达
            </Typography.Text>
            <Typography.Text strong>
              {detail?.edd ? dayjs(detail.edd).format('YYYY-MM-DD') : '2025-02-01'}
            </Typography.Text>
          </Space>
        </Col>
        <Col span={12} style={{ textAlign: 'right' }}>
          <Space direction="vertical" size={4} align="end">
            <Typography.Text type="secondary" className={classNames('small_print', 'small_print_strong')}>
              已预约送达时段
            </Typography.Text>
            <Typography.Text strong>
              {selectedSlot
                ? `${selectedSlot.weekLabel} ${dayjs(selectedSlot.dateRange[0]).format('MM-DD')} ~ ${dayjs(
                    selectedSlot.dateRange[1],
                  ).format('MM-DD')}`
                : '-'}
            </Typography.Text>
          </Space>
        </Col>
      </Row>
      <Row gutter={[16, 16]}>
        {filteredSlots.map(s => {
          const selected = selectedId === s.id
          return (
            <Col key={s.id} span={12}>
              <div
                className={selected ? `${styles.slotCard} ${styles.slotCardSelected}` : styles.slotCard}
                onClick={() => setSelectedId(s.id)}
              >
                <div className={styles.slotCardHeader}>
                  <Space size={8}>
                    <Typography.Text strong>
                      {dayjs(s.dateRange[0]).format('YYYY-MM-DD')} ~ {dayjs(s.dateRange[1]).format('YYYY-MM-DD')}
                    </Typography.Text>
                    <StatusTag status={s.status} />
                  </Space>
                  {selected && (
                    <div className={styles.slotCardCheck}>
                      <CheckCircleFilled />
                    </div>
                  )}
                </div>
                <div className={styles.slotCardBody}>
                  <Row gutter={[0, 8]}>
                    {s.changeDeadline && (
                      <Col span={12}>
                        <Space size={8} direction="vertical">
                          <Space.Compact direction="vertical">
                            <Typography.Text
                              type="secondary"
                              className={classNames('small_print', 'small_print_strong')}
                            >
                              更改截止时间
                            </Typography.Text>
                            <Typography.Text>{s.changeDeadline}</Typography.Text>
                          </Space.Compact>
                        </Space>
                      </Col>
                    )}
                    {s.crowdedEffectiveTime && (
                      <Col span={12}>
                        <Space size={8}>
                          <Space.Compact direction="vertical">
                            <Typography.Text
                              type="secondary"
                              className={classNames('small_print', 'small_print_strong')}
                            >
                              拥挤程度有效时间
                            </Typography.Text>
                            <Typography.Text>{s.crowdedEffectiveTime}</Typography.Text>
                          </Space.Compact>
                        </Space>
                      </Col>
                    )}
                    <Col span={24}>
                      <Space size={8} direction="vertical">
                        <Space.Compact direction="vertical">
                          <Typography.Text type="secondary" className={classNames('small_print', 'small_print_strong')}>
                            ID
                          </Typography.Text>
                          <Typography.Text>{s.id}</Typography.Text>
                        </Space.Compact>
                      </Space>
                    </Col>
                  </Row>
                </div>
              </div>
            </Col>
          )
        })}
      </Row>
      <Divider /> */}
      {/* <div className={styles.actions}>
        <Space>
          <Button type="primary" onClick={reserve}>
            确认预约
          </Button>
          <Button onClick={() => message.info('已获取最新可用送达时段')}>获取可用送达时段</Button>
        </Space>
      </div> */}
      {/* 上传区：ISA / BL */}
      <div className={styles.uploadSection}>
        <Row gutter={16}>
          <Col span={12}>
            <Space direction="vertical" size={8} style={{ width: '100%' }}>
              <Typography.Text strong>ISA</Typography.Text>
              <Input placeholder="请输入 ISA" value={isaVal} onChange={e => setIsaVal(e.target.value)} />
            </Space>
          </Col>
          <Col span={12}>
            <Space direction="vertical" size={8} style={{ width: '100%' }}>
              <Typography.Text strong>BL</Typography.Text>
              <Input placeholder="请输入 BL" value={blVal} onChange={e => setBlVal(e.target.value)} />
            </Space>
          </Col>
        </Row>
      </div>
      <div className={styles.actions}>
        <Space>
          <Button type="primary" onClick={reserve}>
            提交
          </Button>
        </Space>
      </div>
    </Card>
  )
}
